package com.shell.guard.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;

import com.netflix.hystrix.exception.HystrixRuntimeException;

public class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator {
	private static Logger LOGGER = LoggerFactory.getLogger(CustomWebResponseExceptionTranslator.class);

	public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
		HttpHeaders headers = new HttpHeaders();
		OAuth2Exception oAuth2Exception;
		int httpStatus;
		if ((e instanceof HystrixRuntimeException)) {
			Throwable actual = ((HystrixRuntimeException) e).getFallbackException().getCause().getCause();

			oAuth2Exception = new OAuth2Exception(actual.getMessage());
			String code;
			String message;
			if ((actual instanceof AbstractException)) {
				httpStatus = ((AbstractException) actual).getStatus().value();
				code = ((AbstractException) actual).getCode().getCode() + "";
				message = ((AbstractException) actual).getCode().getMessage();
				LOGGER.error("AbstractException", actual);
			} else {
				httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
				code = GenericErrorCodes.GENERIC_API_ERROR_CODE.getCode() + "";
				message = GenericErrorCodes.GENERIC_API_ERROR_CODE.getMessage();
				LOGGER.error("HystrixRuntimeException", actual);
			}
			oAuth2Exception.addAdditionalInformation("code", code);
			oAuth2Exception.addAdditionalInformation("message", message);
		} else {
			ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
			oAuth2Exception = (OAuth2Exception) responseEntity.getBody();
			httpStatus = HttpStatus.UNAUTHORIZED.value();

			String errorCode = oAuth2Exception.getMessage();

			oAuth2Exception.addAdditionalInformation("code", GenericErrorCodes.GENERIC_API_ERROR_CODE.getCode() + "");
			oAuth2Exception.addAdditionalInformation("message", "������������");
			LOGGER.error("OAuth2Exception", oAuth2Exception);
		}
		headers.setContentType(MediaType.APPLICATION_JSON);
		return new ResponseEntity<OAuth2Exception>(oAuth2Exception, headers, HttpStatus.valueOf(httpStatus));
	}
}
